<template>
  <table-toolbar>
    <template #bar-left>
      <div class="big-title">
        <fire-filled class="fire mr-1" />
        <span>关键词热度明细</span>
      </div>
    </template>
  </table-toolbar>
  <a-alert
    class="mb-5"
    v-if="sold"
    message="手机端、电脑端的“部分词的部分城市”已售出，详情如下。若想购买的渠道已售出，请更换已售出关键词/城市重新查价~"
    type="warning"
    show-icon
  />
  <a-table bordered :columns="hotWordColumns" :data-source="tableData" :pagination="false" class="my-table">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'versionSoldAreas'">
        <area-popover ellipsis :areas="getRealAreas(record)" />
      </template>
    </template>
    <template #footer>
      <div class="text-right statistics">
        <span class="mr-5">PC端总热度：{{ pcTotalHeat }}</span>
        <span>移动端总热度：{{ mobileTotalHeat }}</span>
      </div>
    </template>
  </a-table>
</template>

<script lang="ts" setup>
import type { TableProps } from 'ant-design-vue'
import { FireFilled } from '@ant-design/icons-vue'
import AreaPopover from '@/components/area-popover/index.vue'
import TableToolbar from '@/components/table-toolbar/index.vue'
import type { BwWordAsk } from '@/services/price-sheet/getBwPriceAskWords'
import type { PhoenixRegionCheckResult } from '@/services/price-sheet/getPhoenixRegionCheckResult'
import { cloneDeep, groupBy, union } from 'lodash-es'
import { computed, defineOptions } from 'vue'
import { VersionTypeEnum } from '@/core/enums/type'
import { PlatformEnum } from '@/core/enums/platform'
import { PlatformKeyMap } from '@/core/mapper/platform'
import { mapClientTypeToPhoenix } from '@/shared'

interface Props {
  data: BwWordAsk[]
  phoenixChecker: Record<string, PhoenixRegionCheckResult>
  versionType: VersionTypeEnum
}

defineOptions({
  name: 'HotWordDetail'
})

const { Normal, Cheap } = VersionTypeEnum

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  phoenixChecker: () => ({}),
  versionType: VersionTypeEnum.Normal
})

const tableData = computed(() => {
  const hotWords = cloneDeep(props.data)
  // 这里有个业务需求，如果移动端热度低于pc端热度，则移动端热度改为pc端热度
  Object.values(groupBy(hotWords, (d) => d.name)).forEach((withName) => {
    const pc = withName.find((item) => item.clientType === PlatformEnum.PC)
    const mobile = withName.find((item) => item.clientType === PlatformEnum.MOBILE)
    if (pc && mobile) {
      if (pc.heatRate > mobile.heatRate) {
        mobile.heatRate = pc.heatRate
      }
    }
  })

  // 合并标王2.0的关键词已售出城市
  hotWords.forEach((d) => {
    const key = `${d.name}|${mapClientTypeToPhoenix(d.clientType)}`
    const area = props.phoenixChecker[key]?.regionList ?? []

    const makeCheapAreas = d.cheapVersionSoldAreas?.split(',') ?? []
    const makeStandardAreas = d.standardVersionSoldAreas?.split(',') ?? []

    const china = ['全国', '中国']

    if (!makeCheapAreas.some((area) => china.includes(area))) {
      d.cheapVersionSoldAreas = union(area.concat(makeCheapAreas)).toString()
    }

    if (!makeStandardAreas.some((area) => china.includes(area))) {
      d.standardVersionSoldAreas = union(area.concat(makeStandardAreas)).toString()
    }
  })

  return hotWords
})

const sold = computed(() => {
  return tableData.value.some((d) => {
    if (props.versionType === Normal) {
      return d.standardVersionSoldAreas
    }
    if (props.versionType === Cheap) {
      return d.cheapVersionSoldAreas
    }
  })
})

const pcTotalHeat = computed(() => {
  return tableData.value
    .filter((d) => d.clientType === PlatformEnum.PC)
    .reduce((total, d) => {
      total += d.heatRate
      return total
    }, 0)
})

const mobileTotalHeat = computed(() => {
  return tableData.value
    .filter((d) => d.clientType === PlatformEnum.MOBILE)
    .reduce((total, d) => {
      total += d.heatRate
      return total
    }, 0)
})

const hotWordColumns: TableProps['columns'] = [
  {
    title: '关键词',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '渠道',
    dataIndex: 'channelId',
    key: 'channelId',
    customRender: () => '百度'
  },
  {
    title: '平台',
    dataIndex: 'clientType',
    key: 'clientType',
    customRender: ({ text }: { text: PlatformEnum }) => PlatformKeyMap[text]
  },
  {
    title: '关键词热度',
    dataIndex: 'heatRate',
    key: 'heatRate'
  },
  {
    title: '出售城市',
    dataIndex: 'versionSoldAreas',
    key: 'versionSoldAreas',
    ellipsis: true
  }
]

function getRealAreas(record: BwWordAsk) {
  return props.versionType === Normal ? record.standardVersionSoldAreas : record.cheapVersionSoldAreas
}
</script>

<style lang="scss" scoped>
.big-title {
  font-size: 22px;
  color: #ff4d4f;
  line-height: 1.5rem;
  font-weight: bold;
}

.fire {
  color: #ff4d4f;
  font-size: 22px;
}

.my-table {
  ::v-deep(.ant-table-thead > tr > th) {
    background: #fcf8e6;
  }
}

.sold-area-popover {
  width: 200px;
}

.statistics {
  font-size: 14px;
  font-weight: 700;
}
</style>
